package com.strat.searcher.lucene.searching;

import java.io.File;

import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.strat.searcher.lucene.files.FileUtil;
import com.strat.searcher.lucene.querry.QueryFactory;

public class Searcher {

    private int maxMatch = 10;
    private static int defaultMaxMatch = 10;
    private IndexSearcherWrapper searchWrapper;

    private static Logger logger = LoggerFactory.getLogger(Searcher.class);

    public Searcher(IndexSearcherWrapper searchWrapper, int maxMatch) {
        this.searchWrapper = searchWrapper;
        this.maxMatch = maxMatch;
    }

    public Searcher(IndexSearcherWrapper searchWrapper) {
        this.searchWrapper = searchWrapper;
    }

    public TopDocs doSearch(String q) {
        TopDocs hits = this.getHits(q);
        logger.info("Found " + hits.totalHits
                + " document(s)  that matched query '" + q + "':");
        return hits;

    }

    private TopDocs getHits(String q) {
        Query query = QueryFactory.makeQuery(q);
        TopDocs hits = searchWrapper.search(query, this.maxMatch);
        searchWrapper.close();
        return hits;
    }

    public int getMaxMatch() {
        return maxMatch;
    }

    public void setMaxMatch(int maxMatch) {
        this.maxMatch = maxMatch;
    }

    public static void search(File indexDir, String q) {
        IndexSearcherWrapper is = new IndexSearcherWrapper(
                FileUtil.getDirectory(indexDir));
        long start = System.currentTimeMillis();
        Query query = QueryFactory.makeQuery(q);
        TopDocs hits = is.search(query, Searcher.defaultMaxMatch);
        long end = System.currentTimeMillis();
        logger.info("Found " + hits.totalHits + " document(s) (in "
                + (end - start) + " milliseconds) that matched query '" + q
                + "':");
        for (int i = 0; i < hits.scoreDocs.length; i++) {
            ScoreDoc scoreDoc = hits.scoreDocs[i];
            logger.info("Found in doc #" + (scoreDoc.doc) + " with "
                    + scoreDoc.score + " score");
        }
        is.close(); // 9
    }

}
